<?php
namespace app\data\service;
use think\admin\Library;
use app\data\model\DataCatLog;
use app\data\model\DataDeviceLog;
use app\data\model\DataDevice;
use app\data\model\DataCat;
use app\data\model\DataWarningLog;
use app\data\model\DataStatisticsLog;
use app\data\model\DataDeviceCatGroup;
use app\data\service\IotThingService;
use GatewayClient\Gateway;
class EventService
{
    public function set($data,$type){
        if($type == 'Warning'){
            $this->eventWarning($data);
        }
        if($type == 'Log_Post'){
            $this->eventInfo($data);
        }
        if($type == 'Kitten_Protect_Start'){
            $this->KittenProtect($data,'start');
        }
        if($type == 'Kitten_Protect_End'){
            $this->KittenProtect($data,'end');
        }
        if($type == 'Cat'){
            $this->catInOut($data);
        }
        if($type == 'Parameter_Post'){
            $this->ParameterPost($data);
        }
    }
    //统计数据上报
    protected function ParameterPost($data){
        $data_a=[
            'iot_id'=>$data['iotId']
        ];
        if(isset($data['value']['Times_Clean_Day'])){
            //当日清理次数
            $data_a['type'] = 'Times_Clean_Day';
            $data_a['counts'] = $data['value']['Times_Clean_Day'];
        }elseif(isset($data['value']['Times_Clean_Auto_Day'])){
            //当日自动清理次数
            $data_a['type'] = 'Times_Clean_Auto_Day';
            $data_a['counts'] = $data['value']['Times_Clean_Auto_Day'];
        }elseif(isset($data['value']['Times_Clean_Hand_Day'])){
            //当日手动清理次数
            $data_a['type'] = 'Times_Clean_Hand_Day';
            $data_a['counts'] = $data['value']['Times_Clean_Hand_Day'];
        }elseif(isset($data['value']['Times_Clean_Yesterday'])){
            //昨日清理次数
            $data_a['type'] = 'Times_Clean_Yesterday';
            $data_a['counts'] = $data['value']['Times_Clean_Yesterday'];
        }elseif(isset($data['value']['Times_Clean'])){
            //累计清理次数
            $data_a['type'] = 'Times_Clean';
            $data_a['counts'] = $data['value']['Times_Clean'];
        }elseif(isset($data['value']['Times_Smooth_Day'])){
            //当日抚平次数
            $data_a['type'] = 'Times_Smooth_Day';
            $data_a['counts'] = $data['value']['Times_Smooth_Day'];
        }
        //深度杀菌剩余时间
        if(isset($data['value']['Sterilize_Remain_Time'])){
            $uid = DataDevice::mk()->where(['iotId'=>$data['iotId']])->value('member_id');
            $value = $data['value']['Sterilize_Remain_Time'];
            $data_socket=[
                'iotId'=>$data['iotId'],
                'type'=>'process',
                'title'=>'Sterilize',
                'value'=>$value
            ];
            if(Gateway::isUidOnline($uid)){
                Gateway::sendToUid($uid, json_encode($data_socket));
            }
        }else{
            DataStatisticsLog::mk()->insert($data_a);
        }
    }
    //设备异常
    protected function eventWarning($data){
        $value = $data['value']['msg'];
        $msg =config('errorcode.warning');
        DataWarningLog::mk()->insert(['iot_id'=>$data['iotId'],'code'=>$value,'msg'=>$msg[$value]]);
      //  DataDeviceLog::mk()->insert(['iot_id'=>$data['iotId'],'type'=>1,'remark'=>$msg[$value]]);
    }
    //INFO类型事件分配
    protected function eventInfo($data){
        if($data['value']['msg'] <= 4){
            //强制开门（1关门抚平，2自动清理，3手动清理，4定时清理）
        }else if($data['value']['msg'] <=7){
            //关门抚平开始、暂停、结束
        }else if($data['value']['msg'] <=10){
            //开门抚平开始、暂停、结束
        }else if($data['value']['msg'] <=13){
            //自动清理11开始12暂停13结束
        }else if($data['value']['msg'] <=16){
            //手动清理开始、暂停、结束
        }else if($data['value']['msg'] <=19){
            //定时清理开始暂停、结束
        }else if($data['value']['msg'] <=21){
            //自动杀菌开始、结束
        }else if($data['value']['msg'] <=23){
            //手动杀菌开始、结束
        }else if($data['value']['msg'] <=25){
            //定时杀菌开始、结束
        }else{
            return ['msg'=>'未知操作'];
        }
    }
    //幼猫保护开始结束
    protected function KittenProtect($data,$type){
        if($type =='start'){
            $start_time = $data['value']['Time_Kitten_Start'];//时间类型，
            //其他操作
        }else{
            $end_time = $data['value']['Time_Kitten_End'];
            $end_type = $data['value']['End_Manner'];//结束方式：1重量自然消失，2按键继续执行
            //其他操作
        }
    }
    //宠物进出事件
    protected function catInOut($data){
        $model = isset($data['value']['Mode_Clean'])?$data['value']['Mode_Clean']:0;//模式
        $in_time = $data['value']['Time_Cat_In'];//进入事件
        $in_weight = $data['value']['Weight_Cat'];//进入体重
        $out_time = $data['value']['Time_Cat_Out'];//进入事件
        $cat_id = $this->getCatByWeight($data['iotId'],$in_weight);
        //格式化13位时间搓
        $in_time = date("Y-m-d H:i:s", $in_time/1000);
        $out_time = date("Y-m-d H:i:s", $out_time/1000);
        $create_time =  date('Y-m-d H:i:s',$data['time']/1000);

        $data_cat_log = [
            'cat_id'=>$cat_id,
            'iot_id'=>$data['iotId'],
            'in_time'=>$in_time,
            'weight'=>$in_weight*1000,//单位克
            'out_time'=>$out_time,
            'duration'=>strtotime($out_time)-strtotime($in_time),//单位秒
            'create_at'=>$create_time
        ];
        $cat_log_id = DataCatLog::mk()->insertGetId($data_cat_log);
        //添加到总日志
        $log_data=[
            'iot_id'=>$data['iotId'],
            'type'=>2,
            'cat_id'=>$cat_id,
            'log_id'=>$cat_log_id,
            'duration'=>strtotime($out_time)-strtotime($in_time),//单位秒
            'cat_weight'=>$in_weight*1000,//单位克
            'remark'=>'如厕'
        ];
        if($model>0){ //非自动模 直接写入日志
            DataDeviceLog::mk()->insertGetId($log_data);
        }else{
            $log_data['create_at']=$out_time;
            //自动模式 缓存最新一条数据
            $redis = redis();
            $redis->select(1);
            $redis->set('cat_log_'.$data['iotId'], json_encode($log_data));
        }
       // $redis = redis();
        //$redis->select(1);
       // $redis->set('group_'.$data['iotId'], $group_id);
        //如果已知，更新体重
        if($cat_id>0){
            DataCat::mk()->updateWeight($cat_id,$in_weight*1000);
            //更新物模型语音模型
            $info = DataCat::mk()->field('nickname,avatar_thumb,sort,weight,member_id')->where(['id'=>$cat_id])->find();
            $this->send_cat_info($info);
        }
    }
    function send_cat_info($info,$del=0){
        log_result(json_encode($info),'ccc.txt');
        $msg=[];
        if($info['sort']>0){
            $iotIds = DataDevice::mk()->where(['member_id'=>$info['member_id'],'status'=>1])->column('iotId');
            $weight = round($info['weight']/1000, 2);
            $class = new IotThingService();
            $avatar_thumb = $info['avatar_thumb'];
            $avatar_thumb_f = str_replace('./', '/www/wwwroot/tatatest/public/', $avatar_thumb);
            $data=[
                'Cat_ID'=>$info['sort'],
                'Cat_Name'=>$info['nickname'],
                'Cat_Weight'=>$weight,
                'Cat_Picture_Size'=>$avatar_thumb==''?0:filesize($avatar_thumb_f),
                'Cat_Picture'=>$avatar_thumb==''?'':config('iot.host').str_replace('./', '/', $avatar_thumb),
                'Del_ID'=>$del,
            ];
            log_result(json_encode($iotIds),'aaa.txt');
            log_result(json_encode($data),'aaa.txt');
            foreach($iotIds as $k=> $v){
                $res = $class->setService($v,'Cat_Data',json_encode($data));
                log_result(json_encode($res),'bbb.txt');
                $msg[$k]=$res['data']->body->data;
                unset($res);
            }
        }
        return $msg;
    }
    //根据设备ID和猫的重量获取猫的ID
    protected function getCatByWeight($iotId,$weight){
        $weight_setting = sysconf('about.weight_min_max');
        $memberId = DataDevice::mk()->where(['iotId'=>$iotId])->value('member_id');
        $start_weight = $weight*1000-$weight_setting;
        $end_weight = $weight*1000+$weight_setting;
        $cat = DataCat::mk()->where(['member_id'=>$memberId,'is_deleted'=>0])
            ->where('weight','between',[$start_weight,$end_weight])->select()->toArray();
        $count  = count($cat);
        if($count == 1){
            $cat_id =$cat[0]['id'];
            $check_group = DataDeviceCatGroup::mk()->where(['catId'=>$cat_id,'iotId'=>$iotId])->count();
            return $check_group>0?$cat_id:0; //绑定了设备才返回
        }elseif($count == 0){
            return 0;
        }else{
            foreach($cat as $k=>$v){
                $cat[$k]['abs']=abs($weight*1000-$v['weight']);
            }
            $minAge = min(array_column($cat, 'abs'));
            $minColumn = array_reduce($cat, function($carry, $item) use ($minAge) {
                if ($item['abs'] === $minAge) {
                    return $item;
                }
                return $carry;
            });
            $cat_id = $minColumn['id'];
            $check_group = DataDeviceCatGroup::mk()->where(['catId'=>$cat_id,'iotId'=>$iotId])->count();
            return $check_group>0?$cat_id:0;//绑定了设备才返回
        }
    }
}
